﻿using Common;
using EC3_6CLH.Model;
using EC3_6CLH.View;
using System.Windows;

namespace EC3_6CLH
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region 异常处理函数

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
#pragma warning disable CS8604 // 引用类型参数可能为 null。
            MyLog.Error((e.ExceptionObject as Exception)?.InnerException);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
        }

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved();
            MyLog.Error(e.Exception);
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MyLog.Error(e.Exception);
            e.Handled = true;
        }

        #endregion 异常处理函数

        private Mutex? _mutex;
        private string? _message;

        protected override void OnStartup(StartupEventArgs e)
        {
            _mutex = new Mutex(true, nameof(EC3_6CLH), out bool ret);
            if (!ret)
            {
                System.Windows.MessageBox.Show("程序已运行");

                Current.Shutdown();
            }

            //#region 异常处理

            DispatcherUnhandledException += App_DispatcherUnhandledException;

            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            base.OnStartup(e);
            //#endregion 异常处理
            string? sn;
            try
            {
                sn = License.GetSn(Environment.CurrentDirectory + "/license.sn");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            if (License.Check(out _message))
            {
                GlobalValue.LicenseSn = sn ?? string.Empty;
                GlobalValue.LicenseMessage = _message;
                new MainView().Show();
            }
            else
            {
                MessageBox.Show(_message);
                Current.Shutdown();
            }
        }
    }
}